from .pdn import PluginPDN
from .base import *

class PluginDynPs(PluginBase):
    @property
    def Description(self)->str:
        return "动态售电价格机制"
    
    def Initialization(self,elem:ET.Element,inst:TrafficInst,work_dir:Path,plugin_dependency:'list[PluginBase]') -> None:
        assert len(plugin_dependency) == 1 and isinstance(plugin_dependency[0],PluginPDN), "动态售电价格机制依赖一个PDN插件"
        self._pdn = plugin_dependency[0]
        self._grid = plugin_dependency[0].Grid
        self._inst = inst
        self._offset = float(elem.attrib.get("offset",0))
        self.SetPreStep(self.PreStep)
        return None

    def PreStep(self,_t:int,status:PluginStatus)->tuple[bool,None]:
        '''设置_t时刻的售电价格'''
        if status != PluginStatus.EXECUTE: return True, None
        if self._pdn.LastPreStepSucceed:
            Sb_kVA = self._grid.Sb * 1000
            for cs in self._inst.CSList:
                cshd = self._grid.Bus(cs.node).ShadowPrice
                if cshd is None:
                    cs.pbuy.clearOverride()
                else:
                    cs.pbuy.setOverride(cshd/Sb_kVA + self._offset)
            return True, None
        else:
            return False, None